package com.xfcy.blog.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 晓风残月Lx
 * @date 2023/4/18 20:56
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.xfcy.blog.controller")
public class XfcyException {

    /**
     * JSR303的统一异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验除了问题{}，异常类型：{}",e.getMessage(), e.getClass());
        Map<String,String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach( (item) -> {
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(ResultCode.VAILID_EXCEPTION.getCode(),ResultCode.VAILID_EXCEPTION.getDesc()).add("data", map);
    }

    /**
     * 断言的异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public R handleIllegalArgumentException(IllegalArgumentException e){
        log.error("错误：",e);
        return R.error(ResultCode.ASSERT_EXCEPTION.getCode(), e.getMessage());
    }

    /**
     * 登陆异常
     * @param ex
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public R NotLoginExceptionHandler(NotLoginException ex) {
        log.error( " msg : " + ex.getMessage(), ex);
        return R.error(ResultCode.NOT_LOGIN.getCode(),ResultCode.NOT_LOGIN.getDesc());
    }

    /**
     * 自定义异常并处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomerException.class)
    public R handlerCustomerException(CustomerException e) {
        log.error("错误：", e);
        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.error("错误：",e);
        return R.error(ResultCode.UNKOWN_EXCEPTION.getCode(),ResultCode.UNKOWN_EXCEPTION.getDesc()).add("data", e.getMessage());
    }

}
